﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Virgee.Common.Services.Tests.Models;

namespace Virgee.Common.Services.Tests.Support
{
    public class TestApiController : ApiController
    {
        private static List<TestModel> Models = new List<TestModel>();

        static TestApiController()
        {
            Models.Add(new TestModel { Id = 1, Name = "Original Test Model" });
        }

        public List<TestModel> Get()
        {
            return Models;
        }                

        public TestModel Get(int id)
        {
            if (id == -1)
            {
                Thread.Sleep(60000);
                return null;
            }

            var existingModel = Models.SingleOrDefault(m => m.Id == id);
            if (existingModel == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            return existingModel;
        }

        public TestModel Post(TestModel model)
        {
            int newId = Models.Any() ? Models.Max(p => p.Id) + 1 : 1;
            model.Id = newId;
            Models.Add(model);

            return model;
        }

        public TestModel Put(TestModel model)
        {
            var existingModel = Models.SingleOrDefault(m => m.Id == model.Id);
            if (existingModel == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            existingModel.Name = model.Name;
            return existingModel;
        }

        public TestModel Delete(int id)
        {
            var existingModel = Models.SingleOrDefault(m => m.Id == id);
            if (existingModel == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            Models.Remove(existingModel);
            return existingModel;
        }
    }
}
